package simpleconnection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class EchoClient {

	/**
	 * Programme implementant un echo a travers des sockets entre un client et
	 * un serveur. Celui-ci est le client.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Socket mySocket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		//byte[] addr = { (byte) 192, (byte) 168, 0, 58 };
		try {
			 mySocket = new Socket(InetAddress.getByName("localhost"), 4444);
			//mySocket = new Socket(InetAddress.getByAddress(addr), 4444);
			out = new PrintWriter(mySocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(mySocket
					.getInputStream()));
		} catch (UnknownHostException e) {
			System.err.println("Don't know about specified host");
			System.exit(1);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for "
					+ "the connection to the specified host.");
			System.exit(1);
		}

		BufferedReader stdIn = new BufferedReader(new InputStreamReader(
				System.in));
		String userInput, userOutput;
		try {
			while ((userInput = stdIn.readLine()) != null) {
				out.println(userInput);
				userOutput = in.readLine();
				System.out.println("echo from server: " + userOutput);
				if (userOutput.equalsIgnoreCase("Bye.")) {
					System.out
							.println("Client received bye from server and quitting.");
					break;
				}
			}

			out.close();
			in.close();
			stdIn.close();
			mySocket.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

}
